import { Component, Input, Output, EventEmitter, OnInit, OnChanges } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { HttpServcie } from '../../../../service/http.service';
import { Config } from '../../../../service/config';
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import {NoticeBean} from '../../bean/notice.bean';
import {FileUploader,FileItem,ParsedResponseHeaders} from  'ng2-file-upload';
import {Observable} from 'rxjs/Rx';


@Component({
    selector: 'notice-add-page',
    templateUrl: 'notice-add.html',
    styleUrls: ['notice-add.scss']
})
export class NoticeAddPage implements OnInit, OnChanges {
    validateForm: FormGroup;
    isSpinning: boolean=false;
    functions: any = [];
    @Input() inValue: any = [];
    @Output("outPut") outPut = new EventEmitter();
    config:any =Config;
    //系统类型
    searchOptions: any = Config.USER_SEX;
     noticeBean:NoticeBean=new NoticeBean();
    showImage:any=[];
    partyList=[];
     fileUploader = new FileUploader({
        url: Config.IP+Config.API.upload,
        method: "POST",
        itemAlias: "file",
        autoUpload: false,
        headers:[
            {name:"Authorization",value:'Bearer ' + window.localStorage['token']}
        ]
    });
    
    partyRoleOptions:any=[];

    constructor(
        private fb: FormBuilder,
        private httpServcie: HttpServcie,
        private _notification: NzNotificationService
    ) {

    }

    ngOnInit() {
        this.validateForm = this.fb.group({
            title: [null, [Validators.required]],
            content: [null, [Validators.required]],
            fileUrls: [null, [Validators.required]],
            sendUserId:[null, [Validators.required]],
            receiveUserId:[[],[Validators.required]],
            isRead:[null, [Validators.required]],
            anType:[null, [Validators.nullValidator]],
           
        });

        // let partyId = JSON.parse(window.localStorage['notice']).id;
        // let userId = JSON.parse(window.localStorage['notice']).id;
        // Observable.forkJoin(
        //     //查询当前用户拥有的角色
        //     this.httpServcie.findByOwnerOrgList(partyId),
        //     //查询当前用户所属机构下的机构
        //     this.httpServcie.queryPartyByIdList(partyId)
        // ).subscribe(data=>{
        //     if(data[0].status==200){
        //         this.partyRoleOptions =data[0].data;
        //     }
        //     if(data[1].status==200){
        //         //当前机构
        //         this.partyList.push({"partyName":'当前机构',id:partyId});
        //         data[1].data.forEach(element=>{
        //             this.partyList.push(element);
        //         });
        //     }
        // });
    }

    ngOnChanges() {
        this.functions = [];
        if (this.inValue) {
            this.functions = this.inValue;
        }
    }

    queryRoles(partyId){
        if(partyId!=undefined){
            let ob = this.httpServcie.findByOwnerOrgList(partyId);
            ob.subscribe((data)=>{
                this.partyRoleOptions = data.data;
            })
        }else{
            this.partyRoleOptions = [];
        }
        
    }

    submitForm($event, data) {
        //校验是否能提交
        //没有填的标红
        for (const i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
        }
        //处理是否提交
        for (const i in this.validateForm.controls) {
            if(!this.validateForm.controls[i].valid){
                return;
            }
        }

        // if(this.noticeBean.roleList==null){
        //     this.noticeBean.roleList=[];
        // }
        if(this.showImage!=null){
            let urls:string="";
            this.showImage.forEach(element=>{
                urls+=element+",";
            })
            // this.noticeBean.qualificationsUrl=urls.substring(0,urls.length-1);
        }
        this.isSpinning = true;
        let ob = this.httpServcie.addUser(this.noticeBean);
        ob.subscribe((data)=>{
            this.isSpinning = false;
            if(data.status==200){
                this._notification.create('success', '成功提示', '新增成功');
                this.outPut.emit($event);
            }else{
                this._notification.create('error', '失败提示', data.message);
                return;
            }
        })

    }

    //交验
    getFormControl(name) {
        return this.validateForm.controls[name];
    }

    //选择文件后调用的方法
    selectedFileOnChanged(event){
        if(event.target.files[0].type.match('image.*')){
            //手动上传的
            this.fileUploader.uploadAll();
            this.fileUploader.onSuccessItem =(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders)=>{
                    if(status==200){
                        //判断是否是图片
                        if(item.file.type.match('image.*')){
                            this.showImage.push(JSON.parse(response).data);
                            //this.userBean.qualificationsUrl = JSON.parse(response).data;
                        }else{
                            this._notification.create('warning', '警告提示', '请选择图片类型！');
                        }
                    }
            }
        }else {
            this.fileUploader.clearQueue();
            this._notification.create('warning', '警告提示', '请选择图片类型！');
        }
    }

    delete(param){
        this.httpServcie.deleteUpload(param).subscribe(data=>{
            if(data.status==200){
                // this.noticeBean.qualificationsUrl = "";
                this.httpServcie.removeByValue(this.showImage,param);
                //this._notification.create('success', '成功提示', '移除成功');
            }else{
                //this._notification.create('error', '失败提示', data.message);
                return;
            }
        },error=>{

        });
    }


}